package com.ricchieri.lazymodel;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.filter.OperationFilter;
import com.ricchieri.model.Operation;
import com.ricchieri.service.interf.IOperationService;

public class UserAccountStateLazyDataModel extends LazyDataModel<Operation> {
	private static final long serialVersionUID = -5779132303538439246L;
	
	private List<Operation> operations;
	private IOperationService operationService;
	private OperationFilter operationFilter;
	
	public UserAccountStateLazyDataModel(IOperationService operationService, OperationFilter operationFilter) {
		super();
		this.operationFilter = operationFilter;
		this.operationService = operationService;
	}
	
    @Override
    public Object getRowKey(Operation operation) {
        return operation.getId();
    }

    @Override
    public Operation getRowData(String operationId) {
        int id = Integer.valueOf(operationId);

        for (Operation operation : operations) {
            if(id == operation.getId()) {
                return operation;
            }
        }
        return null;
    }
    
	@Override
	public List<Operation> load(int startingAt, int maxPerPage, String sortField, 
			SortOrder sortOrder, Map<String, String> filters) {
		
		if(StringUtils.isNotEmpty(sortField)) {			
			operationFilter.setSortField(sortField);
			operationFilter.setSortOrder(sortOrder.toString());
		}
		
        if(getRowCount() <= 0) {
            setRowCount(getOperationService().getAllOperationCountByFilter(operationFilter));
        }
        
        if(getRowCount() == startingAt && getRowCount()  != 0) {
        	startingAt = startingAt - BusinessSettings.ROW_MAX_RESULT;
        }
		
        operations = getOperationService().getAllOperationPaginatedByFilter(operationFilter, startingAt);

        setPageSize(BusinessSettings.ROW_MAX_RESULT);
        
        return operations;
	}

	public List<Operation> getOperations() {
		return operations;
	}

	public void setOperations(List<Operation> operations) {
		this.operations = operations;
	}

	public IOperationService getOperationService() {
		return operationService;
	}

	public void setOperationService(IOperationService operationService) {
		this.operationService = operationService;
	}

	public OperationFilter getOperationFilter() {
		return operationFilter;
	}

	public void setOperationFilter(OperationFilter operationFilter) {
		this.operationFilter = operationFilter;
	}
}
